package zxing.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.crud.DataSupport;
import org.litepal.util.LogUtil;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.virtualapp.R;
import io.virtualapp.abs.ui.VActivity;
import io.virtualapp.bean.MakeBean;
import io.virtualapp.bean.NumBean;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.util.HttpUtils;
import io.virtualapp.mylibrary.util.ToastUtils;
import okhttp3.Request;
import okhttp3.Response;
import zxing.activity.bean.LoveBean;
import zxing.activity.bean.VoiceFileBean;
import zxing.activity.utils.AudioRecoderUtils;
import zxing.activity.utils.RecordView;
import zxing.activity.utils.SoundRecordView;
import zxing.activity.utils.TimeUtils;
import zxing.activity.utils.WaveLineView;


public class Record1Activity extends VActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener {

    private AudioRecoderUtils mAudioRecoderUtils;
    private MediaPlayer mediaPlayer;
    private static final int SOUND_WHAT = 55;
    int progress;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SOUND_WHAT: {
//                    sound_view.setProgress(progress);
//                    handler.sendEmptyMessageDelayed(SOUND_WHAT, 300);
                    break;
                }
            }
        }
    };
    private List<VoiceFileBean> beans;
    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {
            Manifest.permission.RECORD_AUDIO
    };
    @BindView(R.id.head_back)
    ImageView head_back;
    @BindView(R.id.head_center_title)
    TextView head_center_title;
    @BindView(R.id.mTextView)
    TextView mTextView;
    @BindView(R.id.button_clear)
    Button button_clear;
    @BindView(R.id.button_play)
    Button button_play;
    @BindView(R.id.head_right_title)
    TextView head_right_title;
    Button button;
    @BindView(R.id.recordView)
    WaveLineView sound_view;
    private int countdownTime2 = 59;//倒计时时间，默认时间10秒.这是会变的
    private Timer timeTimer = new Timer(true);
    private Timer progressTimer = new Timer(true);
    private TimerTask timeTask;
    private TimerTask progressTask;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                countdownTime2--;
                mTextView.setText(countdownTime2+"S");
                if (countdownTime2 == 0) {
                    timeTask.cancel();
                    mAudioRecoderUtils.stopRecord();        //结束录音（保存录音文件）
                    // mAudioRecoderUtils.cancelRecord();    //取消录音（不保存录音文件）
                    sound_view.stop();
                    if (handler != null)
                        handler.removeCallbacksAndMessages(null);
                }
            }
        }
    };
    private boolean canSetVolume = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        ButterKnife.bind(this);
//          申请录音权限
        int permission = ActivityCompat.checkSelfPermission(Record1Activity.this,
                Manifest.permission.RECORD_AUDIO);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(Record1Activity.this, PERMISSION_AUDIO,
                    GET_RECODE_AUDIO);
        }
        mAudioRecoderUtils = new AudioRecoderUtils();
        button = findViewById(R.id.button);
        beans = new ArrayList<>();
        if (beans.size() > 0) {
            beans.clear();
        }
        head_right_title.setVisibility(View.VISIBLE);
        head_right_title.setText("生成二维码");
        head_center_title.setText("录音二维码");
        head_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initDatas();
        StartListener();

    }

    public void start() {
        //重置计时器显示的时间
        canSetVolume = true;
        //启动定时器
        timeTimer.schedule(timeTask = new TimerTask() {
            public void run() {
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }, 1000, 1000);

    }

    private boolean isPlay = true;

    protected void initDatas() {

        button_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (beans.size() > 0) {
                    if (isPlay == true) {
                        isPlay = false;
                        mediaPlayerStart(beans.get(0).getFilePath());
                        button_play.setBackground(mContext.getResources().getDrawable(R.mipmap.zanting_play));
                    } else {
                        isPlay = true;
                        mediaPlayerStop();
                        button_play.setBackground(mContext.getResources().getDrawable(R.mipmap.bofang));
                    }
                } else
                    Toast.makeText(Record1Activity.this, "暂无录音，请先录音", Toast.LENGTH_SHORT).show();
            }

        });
        button_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (beans.size() > 0) {
                    showistimeexpirseAlerDialog();
                } else {
                    Toast.makeText(Record1Activity.this, "暂无录音，请先录音", Toast.LENGTH_SHORT).show();
                }
            }
        });
        head_right_title.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                if (beans.size() > 0) {
                    try {
                        UpLoadService(encodeBase64File(beans.get(0).getFilePath()), beans.get(0).getFileName());
//                        saveToFile(fileToString(beans.get(0).getFilePath()),getContext()    );

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(Record1Activity.this, "暂无录音，请先录音", Toast.LENGTH_SHORT).show();
                }

            }
        });
        //录音回调
        mAudioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {
            //录音中....db为声音分贝，time为录音时长
            @Override
            public void onUpdate(double db, long time) {
//                progress = (int) (db / 2);
//                sound_view.setProgress(progress);
//                mTextView.setText(TimeUtils.long2String(time));
//                sound_view.setTime(TimeUtils.long2String(time));
            }

            //录音结束，filePath为保存路径
            @Override
            public void onStop(String filePath) {
                Toast.makeText(Record1Activity.this, "录音保存成功" + filePath, Toast.LENGTH_SHORT).show();
                File file = new File(filePath);
                VoiceFileBean bean = new VoiceFileBean();
                // 获取扩展名
                String FileEnd = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase();
                if (FileEnd.equals("aac")) {
                    bean.setFileName(file.getName());
                    ///storage/emulated/0/record/20181126114528.aac
                    bean.setFilePath(file.getPath());
                    beans.add(bean);
                }
            }
        });
    }

    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return android.util.Base64.encodeToString(buffer, android.util.Base64.DEFAULT);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String fileToString(String path) throws Exception {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;

    }


    private void showistimeexpirseAlerDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("重新录制");
        builder.setMessage("是否删除当前录音，重新录制？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(DialogInterface dialog, int which) {

                beans.clear();
                mTextView.setText("60S");
                countdownTime2=60;
                if (!isPlay && mediaPlayer.isPlaying()) {
                    isPlay = true;
                    mediaPlayerStop();
                    button_play.setBackground(mContext.getResources().getDrawable(R.mipmap.bofang));
                }

                Toast.makeText(Record1Activity.this, "删除成功", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    @Override
    public void onClick(View v) {
    }


    /**
     * 播放音频文件
     */
    private void mediaPlayerStart(String voiceFilePath) {
        mediaPlayer = MediaPlayer.create(this, Uri.parse(voiceFilePath));
        mediaPlayer.setOnCompletionListener(this);
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
    }

    /**
     * 取消播放音频文件
     */
    private void mediaPlayerStop() {
        if (mediaPlayer.isPlaying() || mediaPlayer != null) {
            mediaPlayer.stop();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mp.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            try {
                mediaPlayer.release();
                mediaPlayer.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    public void StartListener() {
        //Button的touch监听
        button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        countdownTime2=60;
                        sound_view.waveAnim();
                        mAudioRecoderUtils.startRecord();

                        start();
                        break;

                    case MotionEvent.ACTION_UP:
                        timeTask.cancel();
                        mAudioRecoderUtils.stopRecord();        //结束录音（保存录音文件）
                        // mAudioRecoderUtils.cancelRecord();    //取消录音（不保存录音文件）
                        sound_view.stop();
                        if (handler != null)
                            handler.removeCallbacksAndMessages(null);
                        break;
                }
                return true;
            }
        });

    }

    private void UpLoadService(String sound, String filename) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtils.getInstance().addSound(
                        sound + "",
                        filename + "",

                        new BaseCallback<LoveBean>() {
                            @Override
                            public void onRequestBefore() {
                            }

                            @Override
                            public void onFailure(Request request, Exception e) {
                                new Handler(getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.showShortToast("提交失败" + e.toString());
                                    }
                                });
                            }

                            @Override
                            public void onSuccess(Response response, LoveBean o) {
                                if (o != null && o.isIssucc()) {
                                    ToastUtils.showShortToast("提交成功");
                                    Record1Activity.this.setResult(RESULT_OK);
                                    String url = o.getData() + "";
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
                                    Date date = new Date(System.currentTimeMillis());
                                    String n = simpleDateFormat.format(date);
                                    MakeBean user = new MakeBean();
                                    user.setName(n);
                                    user.setTit(url + "");
                                    user.save();
                                    NumBean numBean = new NumBean();
                                    if (DataSupport.findFirst(NumBean.class) != null) {
                                        DataSupport.deleteAll(NumBean.class);
                                    }
                                    numBean.setNum(2);
                                    numBean.save();
                                    Intent intent = new Intent(getActivity(), CodeDisplayActivity.class);
                                    intent.putExtra("data", url);
                                    intent.putExtra("title", "录音二维码");
                                    startActivity(intent);
                                } else {
                                    new Handler(getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            ToastUtils.showShortToast("提交失败" + o.getMsg());
                                        }
                                    });
                                }

                            }

                            @Override
                            public void onError(Response response, int errorCode, Exception e) {
                                new Handler(getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.showShortToast("提交失败" + e.toString());
                                    }
                                });
                            }
                        });

            }
        }).

                start();

    }


}
